package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.util.SpecialMapUtil;
import com.fjec.common.view.AnnexBizItem;
import com.fjec.market.entity.*;
import com.fjec.market.es.document.SpuDocument;
import com.fjec.market.es.repository.SpuRepository;
import com.fjec.market.feign.BaseClient;
import com.fjec.market.mapper.InfoBusinessMapper;
import com.fjec.market.mapper.InfoSkuMapper;
import com.fjec.market.service.*;
import org.apache.commons.collections.MapUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 012.商品sku表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-10
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class InfoSkuServiceImpl extends ServiceImpl<InfoSkuMapper, InfoSku> implements IInfoSkuService {

    @Resource
    private InfoSkuMapper mapper;

    @Resource
    private IInfoSpuService infoSpuService;

    @Resource
    private SpuRepository spuRepository;

    @Resource
    private IBizMarketBusiService bizMarketBusiService;

    @Resource
    private IInfoFarmerService infoFarmerService;

    @Resource
    private InfoBusinessMapper infoBusinessMapper;

    @Resource
    private IRefSkuMarketService refSkuMarketService;

    @Resource
    private IBizVisitSpuRecordService bizVisitSpuRecordService;

    @Autowired
    private BaseClient baseClient;

    @Override
    public JsonResult saveSku(InfoSku sku, String spuDesc, Long userId, String skuPics, String skuVideos, String picIds, String videoId) {
        if (sku.getId() == null) {
            int depoStatus = 0;

            Integer busiType = AccountInfo.getBusiType();
            Map m;
            if (busiType == 2) {
                m = infoFarmerService.getFarmerDepoStatusByUserId(userId);
                if (m != null && m.get("DepoStatus") != null)
                    depoStatus = (int) m.get("DepoStatus");
            } else {
                m = infoFarmerService.getBusinessDepoStatusByUserId(userId);
                if (m != null && m.get("DepoStatus") != null)
                    depoStatus = (int) m.get("DepoStatus");
            }

            InfoSpu spu = new InfoSpu();
            if (depoStatus == 1)
                spu.setSaleable(1);
            else
                spu.setSaleable(0);

            spu.setBuisType(AccountInfo.getBusiType());
            spu.setBusiId(AccountInfo.getBusiId());
            spu.setSpuTitle(sku.getSkuTitle());
            spu.setSpuDesc(spuDesc);

            spu.setValid(1);
            spu.setDelFlag(0);
            spu.setUpdateVer(0);
            spu.setWeight(0);
            spu.setCreateTime(DateUtil.nowLdt());
            infoSpuService.save(spu);
            spuRepository.save(new SpuDocument(spu.getId(), spu.getSpuTitle()));

            sku.setSpuId(spu.getId());
            sku.setBusiType(spu.getBuisType());
            sku.setBusiId(spu.getBusiId());
            sku.setSkuTitle(spu.getSpuTitle());
            sku.setDiscount(new BigDecimal(1));
            sku.setAllowCoupon(0);
            sku.setStock(-1);
            sku.setSaleNum(0);
            sku.setUpdateVer(0);
            sku.setSpuPics(Arrays.asList(skuPics.split(",")));
            sku.setSpuVideos(Arrays.asList(skuVideos.split(",")));
            sku.setSaleable(1);
            sku.setValid(1);
            sku.setDelFlag(0);
            sku.setCreateTime(spu.getCreateTime());
            this.save(sku);
            int count = this.count(new QueryWrapper<InfoSku>().eq("BusiId", sku.getBusiId()).eq("DelFlag", 0));

            // 保存商品市场关系表
            List<RefSkuMarket> skuMarkets = new ArrayList<>();
            List<BizMarketBusi> marketBusiList = bizMarketBusiService.list(new QueryWrapper<BizMarketBusi>().eq("BusiId", AccountInfo.getBusiId()));
            for (BizMarketBusi marketBusi : marketBusiList) {
                int markCode = marketBusi.getMarkCode();
                RefSkuMarket refSkuMarket = new RefSkuMarket();
                refSkuMarket.setMarkCode(markCode);
                refSkuMarket.setSpuId(spu.getId());
                skuMarkets.add(refSkuMarket);
            }
            refSkuMarketService.saveBatch(skuMarkets);

            // rpc调用base服务，更改附件启用状态
            List<AnnexBizItem> annexBizItems = new ArrayList<>();
            Arrays.asList(picIds.split(",")).forEach(id -> {
                AnnexBizItem bizItem = new AnnexBizItem();
                bizItem.setAnnexId(Long.valueOf(id));
                bizItem.setBizId(sku.getId());
                bizItem.setBizType(9);
                annexBizItems.add(bizItem);
            });

            AnnexBizItem bizItem = new AnnexBizItem();
            if (videoId != null && !videoId.equals(""))
                bizItem.setAnnexId(Long.valueOf(videoId));
            bizItem.setBizId(sku.getId());
            bizItem.setBizType(10);
            annexBizItems.add(bizItem);
            baseClient.enableAnnexStatus(annexBizItems);
            // end
            return JsonResult.success().message("添加商品成功").total((long) count).build();
        } else {
            InfoSpu spu = new InfoSpu();
            spu.setId(sku.getSpuId());

            spu.setSpuTitle(sku.getSkuTitle());
            spu.setSpuDesc(spuDesc);
            spu.setUpdateTime(DateUtil.nowLdt());
            infoSpuService.updateById(spu);
            spuRepository.deleteById(spu.getId());
            spuRepository.save(new SpuDocument(spu.getId(), spu.getSpuTitle()));

            sku.setSpuPics(Arrays.asList(skuPics.split(",")));
            sku.setSpuVideos(Arrays.asList(skuVideos.split(",")));
            sku.setUpdateTime(DateUtil.nowLdt());
            this.updateById(sku);
            return JsonResult.success().message("更新商品成功").build();
        }
    }

    @Override
    public JsonResult getMySkus(Long busiId) {
        List<InfoSku> skus = this.list(new QueryWrapper<InfoSku>().eq("BusiId", busiId).eq("DelFlag", 0));
        return JsonResult.success().data(skus).total((long) skus.size()).build();
    }

    @Override
    public JsonResult deleteSku(Long skuId, Long spuId) {
        infoSpuService.update(new UpdateWrapper<InfoSpu>().eq("Id", spuId).set("DelFlag", 1));
        this.update(new UpdateWrapper<InfoSku>().eq("Id", skuId).set("DelFlag", 1));
        return JsonResult.success().message("删除商品成功").build();
    }

    @Override
    public int sumSkuSaleNumByBusiId(Long id) {
        return mapper.sumSkuSaleNumByBusiId(id);
    }

    @Override
    public List<Map<String, Object>> getRetailFruits(Integer markCode, List<Long> spuIds, Integer orderBy, Integer dir, Page page) {
        List<Map<String, Object>> result = mapper.getRetailFruits(markCode, spuIds, orderBy, dir, page);
        return result;
    }

    @Override
    public JsonResult getSkuSpuById(Long id) {
        Long userId = 0L;
        if (SecurityUtils.getSubject().isAuthenticated()) {
            userId = AccountInfo.getUserId();
        }

        Map<String, Object> m = mapper.getSkuById(id, userId);
        // 如果商品被逻辑删除，返回错误码
        if (MapUtils.getInteger(m, "DelFlag") == 1) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_3015.getCode())
                    .message(EnumSysCode.ERR_3015.getMsg())
                    .build();
        }
        // end

        m = SpecialMapUtil.lowKey(m);
        // 获取busiType和busiId
        Long busiId = MapUtils.getLong(m, "busiId");
        Integer busiType = MapUtils.getInteger(m, "busiType");
        m.put("busiId", String.valueOf(busiId));
        m.put("spuId", String.valueOf(m.get("spuId")));
        String pics = MapUtils.getString(m, "spuPics");
        if (pics != null) {
            List<String> spuPics = JsonUtil.jsonToObject(pics, List.class);
            m.put("spuPics", spuPics);
        }
        // 处理小视频
        String video = MapUtils.getString(m, "spuVideos");
        if (video != null) {
            List<String> videos = JsonUtil.jsonToObject(video, List.class);
            m.put("spuVideos", videos);
        }
        // 收藏
        if (m.get("favoriteSku") != null)
            m.put("favorite", 1);
        else
            m.put("favorite", 0);
        // add by sz 2020-09-27 for 获取商铺名和商铺图片 start
        switch (busiType) {
            case 2:
                InfoFarmer farmer = infoFarmerService.getById(busiId);
                if (farmer != null) {
                    m.put("shopName", farmer.getShopName());
                    m.put("headPic", farmer.getCompHeadPic());
                    m.put("depoStatus", farmer.getDepoStatus());
                }
                break;
            case 3:
            case 4:
            case 5:
                InfoBusiness business =infoBusinessMapper.selectById(busiId);
                if (business != null) {
                    m.put("shopName", business.getShopName());
                    m.put("headPic", business.getCompHeadPic());
                    m.put("depoStatus", business.getDepoStatus());
                }
                break;
        }
        // add by sz 2020-09-27 for 获取商铺名和商铺图片 end
        m.remove("favoriteSku");

        // 写商品访问记录表

        if (userId != 0L) {
            BizVisitSpuRecord record = new BizVisitSpuRecord();
            record.setSpuId(MapUtils.getLong(m, "spuId"));
            record.setUserId(userId);
            record.setCreateTime(DateUtil.nowLdt());
            bizVisitSpuRecordService.save(record);
        }

        return JsonResult.success().data(m).build();
    }

    @Override
    public JsonResult changePrice(Long id, Integer whole, Integer retail) {
        InfoSku sku = new InfoSku();
        sku.setId(id);
        sku.setWholesalePrice(whole);
        sku.setRetailPrice(retail);
        this.updateById(sku);
        return JsonResult.SUCCESS;
    }

    @Override
    public List<Map<String, Object>> getTop2SkusByShopIds(List<Long> farmerIds) {
        return mapper.getTop2SkusByBusiIds(farmerIds);
    }

    @Override
    public List<Map<String, Object>> getSkusByShopIds(List<Long> farmerIds) {
        return mapper.getSkusByBusiIds(farmerIds);
    }

    @Override
    public List<Map<String, Object>> getSkusBySpuIDsAndMarkCodeAndBusiType(int markCode, int busiType, List<Long> spuIds, int orderBy, int dir, Page page) {
        return mapper.getSkusBySpuIDsAndMarkCodeAndBusiType(markCode, busiType, spuIds, orderBy, dir, page);
    }

    @Override
    public List<Map<String, Object>> getSkuInfoByIdList(List<Long> skuIdList) {
        return mapper.getSkuInfoByIdList(skuIdList);
    }

}
